﻿using System;
using System.Data;

namespace FluentSql
{
    public class NonQueryFluentSqlCommand : BaseFluentSqlCommand, INonQueryFluentSqlCommand
    {
        #region Public Methods

        public int ExecuteNonQuery()
        {
            if (KeepConnection)
            {
                return ExecuteNonQueryImpl(Context.PersistentConnection);
            }
            else
            {
                using (var connection = Context.CreateConnection())
                {
                    return ExecuteNonQueryImpl(connection);
                }
            }
        }

        private int ExecuteNonQueryImpl(IDalSqlConnection iConnection)
        {
            using (var transaction = iConnection.BeginTransaction(IsolationLevel))
            {
                int result = 0;
                using (var command = transaction.CreateCommand(CommandType, Command))
                {
                    SerializeParameters?.Invoke(command);
                    result = command.ExecuteNonQuery();
                }
                transaction.Commit();
                return result;
            }
        }

        public INonQueryFluentSqlCommand SetCommand(string iCommand)
        {
            SetCommandImpl(iCommand);
            return this;
        }

        public INonQueryFluentSqlCommand SetCommandType(CommandType iCommandType)
        {
            SetCommandTypeImpl(iCommandType);
            return this;
        }

        public INonQueryFluentSqlCommand SetContext(IDalContext iContext)
        {
            SetContextImpl(iContext);
            return this;
        }

        public INonQueryFluentSqlCommand SetIsolationLevel(IsolationLevel iIsolationLevel)
        {
            SetIsolationLevelImpl(iIsolationLevel);
            return this;
        }

        public INonQueryFluentSqlCommand SetKeepConnection(bool iKeepConnection)
        {
            SetKeepConnectionImpl(iKeepConnection);
            return this;
        }

        public INonQueryFluentSqlCommand SetParameters(Action<IDalSqlCommand> iSerializeParameters)
        {
            SetParameters(iSerializeParameters);
            return this;
        }

        #endregion Public Methods
    }
}
